//
//  CourseSearchResultViewController.m
//  ShowYork
//
//  Created by hxh on 2020/8/28.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "LessonSearchResultViewController.h"
#import "LessonDetailViewController.h"
#import "LessonResultItemCell.h"
#import "LessonSearchHeader.h"
#import "LessonSearchNavView.h"
#import "LessonSearchFlowLayout.h"
#import "LessonHotCell.h"
#import "LessonPageItemModel.h"
#import "LessonSearchModel.h"
@interface LessonSearchResultViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource,LessonSearchFlowLayoutDelegate,LessonSearchNavViewDelegate,LessonResultItemCellDelegate,LessonSearchHeaderDelegate,LessonHotCellDelegate>
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)LessonSearchNavView *navView;
@property (nonatomic,strong)NSArray *historyDataArr;
@property (nonatomic,strong)NSArray *sourceArray;
@property (nonatomic,strong)NSString *curentContent;
@property (nonatomic,assign)BOOL isSelected;

@property (nonatomic,strong)UIImageView *noDataImgView;
@property (nonatomic,strong)UILabel *noDataLb;

/// 判断搜索按钮点击
@property (nonatomic,assign)BOOL isSearch;

@end

@implementation LessonSearchResultViewController

-(NSArray *)historyDataArr{
    if(!_historyDataArr){
        _historyDataArr = [NSArray array];
    }
    return _historyDataArr;
}
 
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        LessonSearchFlowLayout *layout = [LessonSearchFlowLayout new];
    
        layout.labelFont = [UIFont systemFontOfSize:14];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        //自定义layout初始化
        layout.delegate = self;
        layout.lineSpacing = 8.0;
        layout.interitemSpacing = 10;
        layout.headerViewHeight = 44.0;
        layout.footerViewHeight = 0;
        layout.itemInset = UIEdgeInsetsMake(0, 10, 0, 10);
         
        _collectionView.dataSource = self;
        _collectionView.alwaysBounceVertical = YES;
        [_collectionView registerClass:[LessonResultItemCell class] forCellWithReuseIdentifier:@"Cell"];//cell
        [_collectionView registerClass:[LessonSearchHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LessonSearchHeader"];
        _collectionView.backgroundColor = [UIColor whiteColor];
         
    }
    return _collectionView;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;
    [IQKeyboardManager sharedManager].enable = NO;
    self.navigationController.navigationBar.translucent = NO;
  
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    
    if ([RPAppManager isShowNetworkView]) {
        [self setNetworkErrorUI];
    }else{
        [self setNetworkNormalUI];
    }
    // 监听键盘
    [self registNote];
    
}

- (void)setNetworkNormalUI{
    [self loadRealmData];
}
- (void)setNetworkErrorUI{
    [self showNetworkErrorWithNavTitle:@"" completeBlock:nil cancelBlock:nil];
}

- (void)setUI{
    
    self.isHideNavBar = YES;
    
    self.navView = [[LessonSearchNavView alloc]init];
    self.navView.delegate = self;
    
    [self.view addSubview:self.navView];
    
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
        make.height.mas_equalTo(44);
    }];
    
    [self.view addSubview:self.collectionView];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navView.mas_bottom);
        make.right.equalTo(self.view.mas_right);
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.hidden = YES;
    [self.view addSubview:self.tableView];

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navView.mas_bottom);
        make.right.equalTo(self.view.mas_right);
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    self.view.backgroundColor = RGBA(248, 248, 248, 1);
    self.tableView.backgroundColor = RGBA(248, 248, 248, 1);
    LessonSearchModel *searchModel = [self.hotArray firstObject];
    
    [self.navView setSearchPlaceTitle:searchModel.word];
    
    self.noDataImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"course_noData_tag"]];
    [self.view addSubview:self.noDataImgView];
    
    self.noDataLb = [[UILabel alloc]init];
    self.noDataLb.text = @"无内容";
    self.noDataLb.textColor = C153;
    self.noDataLb.font = font(12);
    self.noDataLb.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.noDataLb];
    
    
    [self.noDataImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    
    [self.noDataLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.noDataImgView.mas_bottom).offset(8);
    }];
    
    self.noDataImgView.hidden = YES;
    self.noDataLb.hidden = YES;
}

- (void)registNote{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
#pragma maark - 监听键盘时间
- (void)keyboardWillShow:(NSNotification *)notification
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CGRect keyboardBounds = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top, 0, keyboardBounds.size.height, 0);
        self.collectionView.contentInset = UIEdgeInsetsMake(self.collectionView.contentInset.top, 0, keyboardBounds.size.height, 0);
    });
}
- (void)keyboardWillHide:(NSNotification *)notification
{
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.collectionView.contentInset = UIEdgeInsetsZero;
}
#pragma mark - 获取本地缓存数据
- (void)loadRealmData{
    RLMResults *results = [[LessonSearchModel allObjects] objectsWhere:[NSString stringWithFormat:@"uuid == %d",[RPAppManager getCustomerId].intValue]];
    NSMutableArray *dataArr = [NSMutableArray array];
    for (LessonSearchModel *model in results) {
        [dataArr addObject:model];
    }
    self.historyDataArr = [dataArr sortedArrayUsingComparator:^NSComparisonResult(LessonSearchModel *obj1, LessonSearchModel *obj2) {
         // 降序排序，最近的时间靠前
        NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:obj2.saveDbTime];
        NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:obj1.saveDbTime];
        return [date2 compare:date1];
    }];
}

#pragma mark - 网络请求
- (void)loadNetwork{
    
    if ([self.curentContent isSpaceString]) {
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:AllSearch];
    param[@"title"] = self.curentContent;
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AllSearch) parames:param success:^(id responseObj) {
        NSArray *arr = [LessonPageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        if (arr.count > 10) {
            self.sourceArray = [arr subarrayWithRange:NSMakeRange(0, 10)];
        }else{
            self.sourceArray = arr;
        }
        if (self.isSearch && self.sourceArray.count == 0) {
            self.noDataImgView.hidden = NO;
            self.noDataLb.hidden = NO;
        }else{
            self.noDataImgView.hidden = YES;
            self.noDataLb.hidden = YES;
        }
        self.isSearch = NO;
        
        [self.tableView reloadData];
        
        
        
    } failure:^(id error) {
        
    }];
}


#pragma mark - tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.sourceArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isSelected) {
        LessonHotCell *cell = [LessonHotCell cellWithTableView:tableView];
        LessonPageItemModel *model = self.sourceArray[indexPath.row];
        model.showIntro = YES;
        [cell setCurrentModel:model];
        [cell isHideLine:indexPath.row == self.sourceArray.count - 1];
        cell.delegate = self;
        return cell;
    }
    NSString *ID = @"SystemId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        cell.textLabel.font = font(14);
        cell.textLabel.textColor = RGBA(51, 51, 51, 1);
    }
    LessonPageItemModel *model = self.sourceArray[indexPath.row];
    cell.textLabel.text = model.title;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  
    if (self.isSelected) {
        
    }else{
        LessonPageItemModel *model = self.sourceArray[indexPath.row];
        LessonSearchModel *newModel = [LessonSearchModel new];
        newModel.id = model.id.intValue;
        newModel.word = model.title;
        [self didSelectedAtCurrentModel:newModel];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

#pragma mark - <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 1) {
        return self.hotArray.count;
    }
    return self.historyDataArr.count;
}
 
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
     
    LessonResultItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    cell.delegate = self;
    if (indexPath.section == 1) {
        [cell setSearchModel:self.hotArray[indexPath.row] atIndex:indexPath.section];
    }else{
        [cell setSearchModel:self.historyDataArr[indexPath.row] atIndex:indexPath.section];
    }
    return cell;
}
 
// 用协议传回 item 的内容,用于计算 item 宽度
- (NSString *)collectionViewItemSizeWithIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        LessonSearchModel *model = self.hotArray[indexPath.row];
        return model.word;
    }
    LessonSearchModel *model = self.historyDataArr[indexPath.row];
    return model.word;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        LessonSearchHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"LessonSearchHeader" forIndexPath:indexPath];
        [header setHeaderTitle:indexPath.section == 0?@"历史搜索":@"热门搜索" andShowDeleteButton:indexPath.section == 0];
        header.delegate = self;
        return header;
    }
    return nil;
}
#pragma mark - CourseSearchHeaderDelegate
- (void)removeSearchData{

    self.historyDataArr = @[];
    
    [self.collectionView reloadData];
    
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm transactionWithBlock:^{
        [realm deleteAllObjects];
    }];
    
    
}
#pragma mark - CourseResultItemCellDelegate

- (void)didSelectedWithCurrentModel:(LessonSearchModel *)currentModel atIndex:(NSInteger)index{
    if (index == 1) {
        [MobClick event:@"lesson_search_hot"];
    }else{
        [MobClick event:@"lesson_search_history"];
    }
    [self didSelectedAtCurrentModel:currentModel];
}

- (void)didSelectedAtCurrentModel:(LessonSearchModel *)currentModel{
    [self.navView textEditing];
    // 这里判断是否有网络
    if ([RPAppManager isShowNetworkView]) {
        [self setNetworkErrorUI];
        return;
    }
    
    self.isSearch = YES;
    
    LessonSearchModel *newModel = [[LessonSearchModel alloc]init];
    newModel.id = currentModel.id;
    newModel.word = currentModel.word;
 
    [self.navView setSearchTitle:currentModel.word];
    // 赋值
    self.curentContent = currentModel.word;
    
    self.collectionView.hidden = YES;
    
    self.isSelected = YES;
    
    self.tableView.hidden = NO;
    
    [self loadNetwork];

    RLMRealm *realm = [RLMRealm defaultRealm];
    RLMResults *results = [[LessonSearchModel allObjects] objectsWhere:[NSString stringWithFormat:@"uuid == %d",[RPAppManager getCustomerId].intValue]];
    if (results.count == 10) {
        [realm transactionWithBlock:^{
            [realm deleteObject:results.firstObject];
        }];
    }
    results = [LessonSearchModel objectsWhere:[NSString stringWithFormat:@"word = '%@'",newModel.word]];
    if (results.count != 0) {
        [realm transactionWithBlock:^{
//            [realm deleteObject:results.firstObject];
            newModel.uuid = [RPAppManager getCustomerId].intValue;
            newModel.saveDbTime = [NSDate date].timeIntervalSince1970;
            [realm addOrUpdateObject:newModel];
        }];
    }else{
        [realm transactionWithBlock:^{
            newModel.uuid = [RPAppManager getCustomerId].intValue;
            newModel.saveDbTime = [NSDate date].timeIntervalSince1970;
            [realm addOrUpdateObject:newModel];
        }];
    }
}

#pragma mark - CourseHotCellDelegate
- (void)selectedCaurseAtCurrentModel:(LessonPageItemModel *)model{
    [MobClick event:@"lesson_show_total" attributes:@{@"enter":@"search_result"}];
    LessonDetailViewController *dtlVC = [[LessonDetailViewController alloc]init];
    dtlVC.lessonId = model.id;
    [self.navigationController pushViewController:dtlVC animated:YES];
}

#pragma mark - CourseSearchNavViewDelegate


-(void)cancel{
    self.isSelected = NO;
    self.noDataImgView.hidden = YES;
    self.noDataLb.hidden = YES;
    if (self.curentContent.length != 0) {
        // 清空填充内容
        [self.navView clearText];
        // 获取本地数据库内容
        [self loadRealmData];
        // 清空查询内容
        self.curentContent = @"";
        // 显示历史记录
        self.collectionView.hidden = NO;
        //  隐藏搜索结果列表
        self.tableView.hidden = YES;
        // 刷新历史记录表
        [self.collectionView reloadData];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)textFieldBeginEditing{
   [self loadRealmData];
}
- (void)textChange:(NSString *)text{
    self.curentContent = text;
    self.noDataImgView.hidden = YES;
    self.noDataLb.hidden = YES;
    self.isSelected = NO;
    [self loadRealmData];
    if (self.curentContent.length == 0) {
        self.collectionView.hidden = NO;
        self.tableView.hidden = YES;
        [self.collectionView reloadData];
    }else{
        self.collectionView.hidden = YES;
        self.tableView.hidden = NO;
        [self loadNetwork];
    }
}

- (void)textSearch:(NSString *)text{

    [self.navView endEditing:YES];
    
    self.isSelected = YES;
    
    self.curentContent = text;

    [self loadRealmData];
    
    self.collectionView.hidden = YES;
    
    self.tableView.hidden = NO;
    
    self.isSearch = YES;
    
    
    LessonSearchModel *newModel = [[LessonSearchModel alloc]init];
    newModel.id = [RPAppManager getCustomerId].intValue;
    newModel.word = text;
 
    RLMRealm *realm = [RLMRealm defaultRealm];
    RLMResults *results = [[LessonSearchModel allObjects] objectsWhere:[NSString stringWithFormat:@"uuid == %d",[RPAppManager getCustomerId].intValue]];
    if (results.count == 10) {
        [realm transactionWithBlock:^{
            [realm deleteObject:results.firstObject];
        }];
    }
    results = [LessonSearchModel objectsWhere:[NSString stringWithFormat:@"word = '%@'",newModel.word]];
    if (results.count != 0) {
        [realm transactionWithBlock:^{
            newModel.uuid = [RPAppManager getCustomerId].intValue;
            newModel.saveDbTime = [NSDate date].timeIntervalSince1970;
            [realm addOrUpdateObject:newModel];
        }];
    }else{
        [realm transactionWithBlock:^{
            newModel.uuid = [RPAppManager getCustomerId].intValue;
            newModel.saveDbTime = [NSDate date].timeIntervalSince1970;
            [realm addOrUpdateObject:newModel];
        }];
    }
    
    
    [self loadNetwork];
}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}
@end
